<?php
/*
 *   This file is part of verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 	 Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 */
 
$cadena = dirname(__FILE__);
$fpos = strrpos($cadena, "/");
if ($fpos<=0) {
	$cadena = str_replace("\\","/",$cadena);
	$fpos = strrpos($cadena, "/");
}

define('ROOT_PATH',substr($cadena, 0, $fpos)."/");
 
require_once(ROOT_PATH."includes/session.php");
require_once(ROOT_PATH."func/sessioncache.php"); 
require_once(ROOT_PATH."includes/util.func.php");
require_once(ROOT_PATH."func/functions.inc.php");
require_once(ROOT_PATH."func/filefunctions.inc.php");
require_once(ROOT_PATH."includes/mail.inc.php");

require_once(ROOT_PATH."configs/config.php");
//require_once(ROOT_PATH."configs/lang.php");

$param=util::fillparam();

function __autoload($class_name) {
	$include_path = ROOT_PATH."class/";
	$path = $include_path . $class_name . '.class.php';
	if(file_exists($path)){
		require_once $path;
	} 
}

function makevalue($array,$fields) {
	$sql = "";
	foreach ($fields as $s) {
		if ($sql!="") $sql.=",";
		if ($s=="") {
			$sql.="NULL";
		} else {
			$sql.=util::str($array[$s]);	
		}
	}
	return "VALUES (".$sql.")";
}

$_log =& LoggerManager::getLogger('default');

$CONFFILE = ROOT_PATH."configs/dbconf1.php";

$_log->info("INIT SETUP");
$_log->debug($param);

if ($param['op']="save") {
	$dbuser = $param['dbusername'];
	$dbpass = $param['dbpassword'];
	$dbhost = $param['dbhost'];

	$sdbname = $param['sdbname'];
	$tdbname = $param['tdbname'];
	
	$_log->info("TEST CONNECT");
	$db = new dbmanager($dbhost,$dbuser,$dbpass);
	
	$_log->info("TEST $sdbname");
	if (!$db->testConnect($sdbname)) die($db->error);
	$_log->info("TEST $tdbname");
	if (!$db->testConnect($tdbname)) die($tdb->error);
	
	$db->connect($tdbname);
	$loader = new loader($db);
	
	/* USERS */
	$_log->debug("Users");
	$sql = "SELECT * FROM $sdbname.users";
	$slist = $loader->fetchlist($sql);
	
	$a=0;
	foreach ($slist as $su) {
		if ($su->userid!="admin") {
			$sql = "INSERT INTO $tdbname.".USERS." (userid, mail, password, groupid, timezone, lang, teamid, status,lastlogin) ";
			$sql .= "VALUES (".util::str($su['userid']).",".util::str($su['mail']).",".util::str($su['password']).",";
			$sql .= util::str($su['groupid']).",".util::str($su['timezone']).",".util::str($su['lang']).",".util::str($su['teamid']);
			$sql .= ",".util::str($su['status']).",".util::str($su['lastlogin']).")";
			$a += $loader->execute($sql);	
		}
	}
	$_log->info("Users: " . $a);
	
	/* TEAMS */
	$_log->debug("Teams");
	$sql = "SELECT * FROM $sdbname.teams ORDER BY id";
	$slist = $loader->fetchlist($sql);
	
	$a=0;
	foreach($slist as $st) {
		$sql = "INSERT INTO $tdbname.".TEAMS." (id,name,status,lang) ";
		$sql .= "VALUES (".util::str($st['id']).",".util::str($st['name']).",".util::str($st['status']).",".util::str($st['lang']).")";
		$a += $loader->execute($sql);	
	}
	$_log->info("Teams: " . $a);
	
	/* PROJECTS */
	$_log->debug("Projects");
	$sql = "SELECT * FROM $sdbname.projects ORDER BY id";
	$slist = $loader->fetchlist($sql);
	
	$a=0;
	foreach($slist as $st) {
		$sql = "INSERT INTO $tdbname.".PROJECTS." (id,parent,name,path,status,statsupdated) ";
		$sql .= makevalue($st,array('id','parent','name','path','status','statsupdated'));
		$a += $loader->execute($sql);	
	}
	$_log->info("Projects: " . $a);	
	
	/* LANGUAGES */
	$_log->debug("Languages");
	$sql = "SELECT * FROM $sdbname.languages ORDER BY id";
	$slist = $loader->fetchlist($sql);
	
	$a=0;
	foreach($slist as $st) {
		$sql = "INSERT INTO $tdbname.".LANGUAGE." (id) ";
		$sql .= makevalue($st,array('id'));
		$a += $loader->execute($sql);	
	}
	$_log->info("Languages: " . $a);	

	/* GLOSSARY */
	$_log->debug("Glossary");
	$sql = "SELECT * FROM $sdbname.glossary ORDER BY id";
	$slist = $loader->fetchlist($sql);
	
	$a=0;
	foreach($slist as $st) {
		$sql = "INSERT INTO $tdbname.".GLOSSARY." (id,english_term,translation,context,related,comments,lastupdate,userid,teamid) ";
		$sql .= makevalue($st,array('id','english_term','translation','context','related','comments','lastupdate','lastuserid','teamid'));
		$a += $loader->execute($sql);	
	}
	$_log->info("Glossary: " . $a);
				
	/* FILES */
	$includeData=true; 
	include_once(ROOT_PATH."configs/dbdefines.php");

	$_log->debug("Files");
	$prj = new project;
	$plist = $loader->loadList($prj);

	$_log->debug("Total projects: ".count($plist));
	
	$stlist = array(FILE_STATUS_TODO,FILE_STATUS_DONE);

	$a=0;
	foreach ($plist as $prj) {
		$fsource = $sdbname.".".FILES."_PRJ".$prj->id;
		$ftarget = FILES.PROJECT_PREFIX.$prj->id;
		$hsource = $sdbname.".".HISTORY."_PRJ".$prj->id;
		$htarget = HISTORY.PROJECT_PREFIX.$prj->id;
		if ($db->exists($fsource)) {
			if (!$db->exists($ftarget)) {
				$query = String::format($table_def['FILES']['def'],$ftarget);
				$db->query($query);
				$query = String::format($table_def['HISTORY']['def'],$htarget);
				$db->query($query);				
			}
			//$sql = "SELECT * FROM ".$fsource;
			$sql = "select f.*,h.userid as fuser from $fsource f left join $hsource h on f.id = h.fileid group by f.id";			
			$slist = $loader->fetchlist($sql);
			foreach ($slist as $st) {
				$sql = "INSERT INTO ".$ftarget." (id,name,comment,statusid,userid,userid2,teamid,prjid,lastupdate,chstamp,translated,untranslated,fuzzy,autoflag) ";
				if (!in_array($st['statusid'],$stlist)) {
					$sql .= makevalue($st,array('id','name','comment','statusid','fuser','','teamid','prjid','lastupdate','chstamp','translated','untranslated','fuzzy','autoflag'));	
				} else {
					$sql .= makevalue($st,array('id','name','comment','statusid','','','teamid','prjid','lastupdate','chstamp','translated','untranslated','fuzzy','autoflag'));
				}
				$a += $loader->execute($sql);
			}
			$sql = "SELECT * FROM ".$hsource;
			$slist = $loader->fetchlist($sql);
			foreach ($slist as $st) {
				$sql = "INSERT INTO ".$htarget." (id, fileid, comment, statusid, userid, date) ";
				$sql .= makevalue($st,array('id','fileid','comment','statusid','userid','date'));	
				$a += $loader->execute($sql);
			}
		} else {
			$_log->debug($prj->id." does not exists.");
		}
	}
	$_log->info("Files: " . $a);
	
	$db->close();

	echo "Migration Complete!!";
	
}


?>
